import tool from '@/utils/tools';
import Dialog from 'tdesign-miniprogram/dialog/index';
import Message from 'tdesign-miniprogram/message/index';

import intervalStore from '@/store/interval';
import { createStoreBindings } from '@/miniprogram_npm/mobx-miniprogram-bindings/index';

import { getValidateCode, checkValidateCode, resetUserPassword } from '@/service/api/user';

const messageDefaultConfig = (content) => {
    return {
        content: content,
        offset: [60, 32],
        duration: 2000
    };
};
let validateChecked = false;
const passwordPattern = /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,}$/;
const emailPattern = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}/;

Page({
    data: {
        registerEmail: '',
        newPassword: '',
        confirmedPassword: '',
        validateCode: ''
    },

    onLoad() {
        this.storeBindings = createStoreBindings(this, {
            store: intervalStore,
            fields: ['currentSecond'],
            actions: ['setNewInterval', 'clearInterval']
        });
    },

    onUnload() {
        this.storeBindings.destroyStoreBindings();
    },

    goBack() {
        wx.navigateBack();
	},

    handleSubmit: tool.throttle(async function () {
        const that = this.data;
        if (!emailPattern.test(this.data.registerEmail)) {
            Message.error(messageDefaultConfig('请输入正确格式的邮箱地址'));
            return;
        }
        if (!passwordPattern.test(this.data.newPassword)) {
            Message.error(messageDefaultConfig('密码长度至少8位，使用字母数字组合'));
            return;
        }
        if (that.newPassword !== that.confirmedPassword) {
            Message.error(messageDefaultConfig('两次输入的密码不一致'));
            return;
        }
        if (!validateChecked) {
            Message.error(messageDefaultConfig('请完成邮箱校验'));
            return;
        }
        if (!/\d{4}/.test(this.data.validateCode)) {
            Message.error(messageDefaultConfig('请输入4位数字验证码'));
            return;
        }
        try {
            await checkValidateCode(this.data.registerEmail, this.data.validateCode);
            const data = {
                character: this.data.registerEmail,
                password: this.data.newPassword
            };
            await resetUserPassword(data);
            Dialog.confirm({
                title: '重置密码',
                closeOnOverlayClick: false,
                content: '密码重置成功，请返回登陆',
                confirmBtn: '确定'
            }).then(() => {
                this.clearInterval();
                wx.reLaunch({
                    url: '/pages/login/login'
                });
            });
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    }, 1500),

    // 获取邮箱验证码
    async getValidateCode() {
        if (!emailPattern.test(this.data.registerEmail)) {
            Message.error(messageDefaultConfig('请输入正确格式的邮箱地址'));
            return;
        }
        if (this.data.currentSecond !== 0) {
            return;
        }
        try {
            // 发送短信验证码
            await getValidateCode(this.data.registerEmail);
            this.setNewInterval(60);
            validateChecked = true;
            Message.success(messageDefaultConfig('验证码已发送，注意查看邮箱'));
        } catch (err) {
            Message.error(messageDefaultConfig(err.message));
        }
    }
});
